<template>
  <div class="form-container">
    <!-- 头部搜索 -->
    <div class="table-head">
      <el-form class="table-form" v-permission="['203004']">
        <el-form-item label="用户名称">
          <el-input v-model="keyWords.username"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="keyWords.role" placeholder="用户角色" style="width: 110px">
            <el-option :label="item.name" :value="item.remark" v-for="item in roles" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="keyWords.status" placeholder="用户状态" style="width: 110px">
            <el-option label="正常" :value="true"></el-option>
            <el-option label="停用" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="keyWords.createdAt"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-button type="primary" plain icon="Search" @click="handelSearch">搜索</el-button>
        <el-button type="warning" plain icon="Refresh" @click="handelRefresh(keyWords)">重置</el-button>
      </el-form>
      <!-- 增删改查按钮组 -->
      <el-row class="btns">
        <el-button v-permission="['203001']" type="primary" plain icon="Plus" @click="add">增加</el-button>
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="multipleSelection.length>1 ||multipleSelection.length===0 "
          @click="edit(null)"
          v-permission="['203002']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multipleSelection.length===0"
          @click="del"
          v-permission="['203003']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="importExcel"
          v-permission="['203005']"
        >导入Excel</el-button>
        <el-button
          type="success"
          plain
          icon="Download"
          @click="exportExcel"
          v-permission="['203006']"
        >导出Excel</el-button>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="userlist" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="用户编号" type="index" :index="indexMethod" width="100" />
        <el-table-column label="用户名称" prop="username"></el-table-column>
        <el-table-column label="用户头像" prop="avatar">
          <template #default="scope">
            <img :src="scope.row.avatar" class="avatar" alt srcset />
          </template>
        </el-table-column>
        <el-table-column label="用户状态" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              class="ml-2"
              inline-prompt
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="联系方式" prop="phone">
          <template #default="scope">{{scope.row.phone}}</template>
        </el-table-column>
        <el-table-column label="用户角色" prop="roles" width="180">
          <template #default="scope">
            <template v-for="item in  scope.row.roles" :key="item.id">
              <el-tag class="tag" :type="item.remark==='admin'?'success':'info'">{{item.name}}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt"></el-table-column>
        <el-table-column fixed="right" label="操作" width="260">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              :enterable="false"
              effect="dark"
              content="删除用户"
              placement="top-start"
            >
              <el-button
                type="danger"
                v-permission="['203003']"
                size="small"
                icon="Delete"
                @click="del(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              :enterable="false"
              effect="dark"
              content="修改信息"
              placement="top-start"
            >
              <el-button
                type="warning"
                v-permission="['203002']"
                size="small"
                icon="Edit"
                @click="edit(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              :enterable="false"
              effect="dark"
              content="分配权限"
              placement="top-start"
            >
              <el-button
                type="warning"
                v-permission="['203002']"
                size="small"
                icon="Setting"
                @click="permission(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              :enterable="false"
              effect="dark"
              content="修改密码"
              placement="top-start"
            >
              <el-button
                type="warning"
                v-permission="['203002']"
                size="small"
                icon="Key"
                @click="changePwd(scope.row)"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              class="box-item"
              :enterable="false"
              effect="dark"
              v-permission="['203008']"
              content="用户详情"
              placement="top-start"
            >
              <el-button type="warning" size="small" icon="User" @click="goDeatail(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格分页 -->
      <table-pagination
        :pagination="pagination"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
      <el-form ref="ruleFormRef" :model="UserForm" :rules="rules" label-width="120px">
        <el-form-item label="用户名称:" prop="username">
          <el-input v-model="UserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="phone">
          <el-input v-model="UserForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="头像链接:" prop="avatar">
          <el-input v-model="UserForm.avatar"></el-input>
        </el-form-item>
        <el-form-item label="用户角色:" prop="roles">
          <template #default="scope">
            <el-checkbox-group v-model="CheckBoxRoleIds" @change="change">
              <el-checkbox :label="item.name" v-for="item in roles" :key="item.id" />
            </el-checkbox-group>
          </template>
        </el-form-item>
        <!-- 用户角色修改 多选框 -->
        <el-form-item label="用户角色:" prop="status">
          <el-radio-group v-model="UserForm.status">
            <el-radio :label="true">正常</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(UserForm)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog v-model="setRole" title="分配角色" width="30%" :before-close="handleClose">
      <el-form ref="ruleFormRef" :model="UserForm" :rules="rules" label-width="120px">
        <el-form-item label="用户角色:" prop="roles">
          <template #default="scope">
            <el-checkbox-group v-model="CheckBoxRoleIds" @change="change">
              <el-checkbox :label="item.name" v-for="item in roles" :key="item.id" />
            </el-checkbox-group>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(UserForm)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入Excel弹框 -->
    <import-data
      :showExcel="showExcel"
      :rolelistAll="rolelistAll"
      @onSucess="onSucess"
      @cancel="cancel"
      @confirm="confirm"
    ></import-data>
    <!-- 导出Excel弹框 -->
    <export-data
      :showExcelOut="showExcelOut"
      :rolelistAll="rolelistAll"
      :excleConfig="USER_RELTIVES"
      @cancel="cancel"
      @confirm="confirm"
    ></export-data>
  </div>
</template>

<script setup>
import ImportData from '@/components/Excel/importData.vue'
import ExportData from '@/components/Excel/exportData.vue'
import { generater } from '@/components/Excel/utils.js'
import { USER_RELTIVES } from '@/excleConfig'
import TablePagination from '@/components/sysCommom/tablePagination.vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  getUserlist,
  UpdateUser,
  SearchUser,
  addUser,
  delUser,
  addUserList,
  getUserlistAll,
  updatePwd,
} from '@/api/user.js'
import { getRolelist } from '@/api/sysRole.js'
import { ElMessage, ElMessageBox } from 'element-plus'
// 创建路由对象
const router = new useRouter()
// 数据列表
const userlist = ref([])
// 关联的角色种类
const roles = ref([])
// 导出数据列表
const rolelistAll = ref([])
// 弹框显示隐藏
const dialogVisible = ref(false)
const setRole = ref(false)
// 弹出框标题
const title = ref('添加用户')
// 表单实例对象
const ruleFormRef = ref()
// 显示导入Excel
let showExcel = ref(false)
// 显示导出Excel
let showExcelOut = ref(false)

// 多选框的值
const CheckBoxRoleIds = ref([])
const UserForm = reactive({
  id: undefined,
  username: '',
  phone: '',
  avatar: '',
  roleIds: [],
  status: true,
})
// 批量选择容器
const multipleSelection = ref([])
// 存储修改对象
const multipleSelectionObj = ref([])
// 分页参数
const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 8,
})
// 搜索词
let keyWords = reactive({
  username: '',
  phone: '',
  status: '',
  role: '',
  createdAt: null || [],
})
// 获取角色
const getroles = async () => {
  const {
    data: { rows },
  } = await getRolelist()
  roles.value = rows
}
getroles()
// 监听多选框的事件 获取角色的id
const change = (val) => {
  let arr = []
  val.forEach((element) => {
    roles.value.forEach((item) => {
      if (item.name == element) {
        arr.push(item.id)
      }
    })
  })
  UserForm.roleIds = arr
}
// 处理关闭弹框
const handleClose = () => {
  resetForm(UserForm)
  dialogVisible.value = false
  setRole.value = false
}
// 添加方法
const add = () => {
  title.value = '添加用户'
  dialogVisible.value = true

  getroles()
}
// 修改
const edit = (row) => {
  title.value = '修改用户'
  const roleIds = row ? row : multipleSelectionObj.value[0]
  for (const key in UserForm) {
    if (UserForm[key] != roleIds) UserForm[key] = roleIds[key]
  }
  UserForm.roleIds = CheckBoxRoleIds.value
  for (let index = 0; index < roleIds.roles.length; index++) {
    CheckBoxRoleIds.value.push(roleIds.roles[index].name)
  }
  dialogVisible.value = true
  getroles()
}
// 开关事件
const handleStatusChange = async (roleObj) => {
  const data = await UpdateUser({
    id: roleObj.id,
    status: roleObj.status,
  })

  if (data.code === 200) {
    ElMessage.success(data.msg)
  }
}
// 搜索事件
const handelSearch = async () => {
  if (keyWords.createdAt.length === 2) {
    keyWords['begin'] = dateFormat(keyWords.createdAt[0])
    keyWords['end'] = dateFormat(keyWords.createdAt[1])
  }

  const { data } = await SearchUser(keyWords)
  if (data.rows.length > 0) {
    userlist.value = data.rows
    pagination.total = data.count
    ElMessage.success('查询成功')
  } else {
    userlist.value = data.rows
    ElMessage.error('暂无查询结果')
  }
}
// 搜索条件重置事件
const handelRefresh = (object) => {
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      if (object[key] != true) object[key] = ''
    }
  }
  users()
}
// 获取用户
const users = async () => {
  const {
    data: { count, rows },
  } = await getUserlist(pagination)
  userlist.value = rows
  pagination.total = count
}
users()
// 跳转到用户详情
const goDeatail = (row) => {
  router.push('/home/userdetail/' + row.id)
}
// 删除用户
const del = (row) => {
  ElMessageBox.confirm('确定要永久删除此条记录，操作不可恢复?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const roleIds = row.id || multipleSelection.value
      const data = await delUser({ ids: roleIds })

      if (data.code === 200) {
        ElMessage.success(data.msg)
        users()
      }
    })
    .catch(() => {})
}
// 修改密码
const changePwd = async (row) => {
  ElMessageBox.prompt(`请为 ${row.username} 用户输入新的密码`, '修改秘密', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /[0-9a-zA-Z]{6,}/,
    inputErrorMessage: '至少6为',
  })
    .then(async ({ value }) => {
      const { id } = row
      const { data } = await updatePwd({ id, password: value })
      if (data.code == 200) {
        ElMessage.success(data.msg)
      }
    })
    .catch(() => {})
}
// 用户权限
const permission = (row) => {
  setRole.value = true
  const roleIds = row ? row : multipleSelectionObj.value[0]
  for (const key in UserForm) {
    if (UserForm[key] != roleIds) UserForm[key] = roleIds[key]
  }
  UserForm.roleIds = CheckBoxRoleIds.value
  for (let index = 0; index < roleIds.roles.length; index++) {
    CheckBoxRoleIds.value.push(roleIds.roles[index].name)
  }
}

// 表单排序
const indexMethod = (index) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1
}
// 批量删除选择事件
const handleSelectionChange = (selection) => {
  const ids = selection.map((item) => item.id)
  multipleSelectionObj.value = selection
  multipleSelection.value = ids
}
// 表单提交事件
const submitForm = (formEl) => {
  formEl.validate(async (valid) => {
    if (!valid) return
    let data
    if (!UserForm.id) {
      // 添加
      data = await addUser(UserForm)
    } else {
      // 修改
      data = await UpdateUser(UserForm)
    }
    if (data.code === 200) {
      ElMessage.success(data.msg)
      resetForm(UserForm)
      users()
    }
    dialogVisible.value = false
    setRole.value = false
  })
}
// 导入Excel显示弹框
const importExcel = () => {
  showExcel.value = true
}
// 导出Excel显示弹框 传递数据
const exportExcel = async () => {
  const { data } = await getUserlistAll()
  rolelistAll.value = data
  showExcelOut.value = true
}
// 接收子组件取消 关闭弹出框的事件
const cancel = () => {
  showExcel.value = false
  showExcelOut.value = false
}
// 接收子组件的确定事件 关闭弹框
const confirm = () => {
  showExcel.value = false
  showExcelOut.value = false
}
//导入excel数据 成功的回调函数
const onSucess = async (excelDate) => {
  //excel 数据
  const { results } = excelDate
  const res = generater(results, USER_RELTIVES)
  // 批量插入接口
  const data = await addUserList({ users: res, condition: 'username' })
  if (data.code === 200) {
    confirm()
    ElMessage.success(`一共插入${data.inserCount}条数据`)
    users()
  }
}
// 表单重置
const resetForm = (object) => {
  for (const key in object) {
    if (Object.hasOwnProperty.call(object, key)) {
      if (object[key] != true) object[key] = ''
    }
  }
  //清空多选框数据
  CheckBoxRoleIds.value = []
  dialogVisible.value = false
}
// 表单验证规则
const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名称',
      trigger: 'blur',
    },
    {
      max: 20,
      message: '最大20 个字符',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入用户标识',
      trigger: 'blur',
    },
    {
      min: 11,
      max: 11,
      message: '请输入正确格式',
      trigger: 'blur',
    },
  ],
  avatar: [
    {
      required: true,
      message: '请输入用户描述',
      trigger: 'blur',
    },
  ],
  status: [
    {
      required: true,
      message: '请选择用户状态',
      trigger: 'blur',
    },
  ],
})
// 时间的格式化
const dateFormat = (dateData) => {
  var date = new Date(dateData)
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  var d = date.getDate()
  d = d < 10 ? '0' + d : d
  const time = y + '-' + m + '-' + d
  return time
}
// 分页处理-页码改变
const handleSizeChange = (val) => {
  pagination.currentPage = 1
  pagination.pageSize = val
  users()
}
// 分页处理-每页条数改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  users()
}
</script>
<style lang="less" scoped>
.el-form .el-form-item {
  margin-right: 15px;
}
.form-container {
  margin: 15px;
}
.btns {
  margin: 10px 0;
}
.table-form {
  display: flex;
}
.pagination {
  margin-top: 15px;
  float: right;
}
.avatar {
  width: 65px;
  height: 65px;
  border-radius: 50%;
}
.tag {
  margin: 5px;
}
</style>